package com.example.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.exam.Exam;
import com.example.domain.exam.dto.ExamQueryDTO;
import com.example.domain.exam.vo.ExamVO;
import com.example.domain.user.UserExam;
import com.example.manager.ExamCacheManager;
import com.example.mapper.exam.ExamMapper;
import com.example.mapper.user.UserExamMapper;
import com.example.security.exception.ServiceImplException;
import com.example.security.service.TokenService;
import com.example.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.JwtConstants;
import oj.common.core.domain.TableDataInfo;
import oj.common.core.enums.ExamListType;
import oj.common.core.enums.ResultCode;
import oj.common.core.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ExamCacheManager examCacheManager;


    @Override
    public int enter(String token, Long examId) {
       Exam exam = examMapper.selectById(examId);
       if(exam == null){
           throw new ServiceImplException(ResultCode.EXAM_NOT_EXISTS);
       }
       if(exam.getStartTime().isBefore(LocalDateTime.now())){
           throw new ServiceImplException(ResultCode.EXAM_STARTED);
       }
       Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID,Long.class);
       //这要进行查询
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examId));
        if(userExam != null) {
            throw new ServiceImplException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId,examId);
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examId);
        return  userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //这里进行刷新缓存
        //缓存在设置的时候，value存放的是一个examId方便后面去取。
        Long userId  = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID,Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        //至于这句话是因为查询用户竞赛列表的时候，需要用到一个type字段，这还是前面查询历史竞赛和未完赛的竞赛需要的一个type字段。
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        log.info("total:"+total);
        List<ExamVO> examVOList;
        if(total==null || total<=0) {
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            //直接从缓存中拿取数据
            //去缓存中拿数据有问题
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        //这里将报名设置为一个true
        for (ExamVO examVO : examVOList) {
            examVO.setEnter(true);
        }
        return TableDataInfo.success(examVOList,total);
    }
}
